package org.ala.tiktools.rpc.netty.handler;

import org.ala.tiktools.rpc.exception.RpcWriteException;
import org.ala.tiktools.rpc.msg.RpcMsg;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author ala
 * @date 2025-04-08 12:31
 */
@SuppressWarnings("rawtypes")
public class RpcMsgEncoder extends MessageToByteEncoder<RpcMsg> {


//    static Logger log = LoggerFactory.getLogger("rpc", "decoder_encoder");


    @SuppressWarnings({ "unchecked"})
	@Override
    protected void encode(ChannelHandlerContext ctx, RpcMsg msg, ByteBuf out) throws Exception {
        IRpcMsgDecoderEncoder de = IRpcMsgDecoderEncoder.mapper.get(msg.getHead().getType());
        if (de == null) {
//            log.error(String.format("无法解析消息类型 type:%s", msg.getHead().getType()));
            throw new RpcWriteException(String.format("无法解析消息类型 type:%s", msg.getHead().getType()));
        }
        try {
            de.encoder(msg, out);
//            log.info("[RpcMsgEncoder encode] 发送消息:{}", msg.getHead());
        } catch (Exception e) {
//            log.error("[RpcMsgEncoder encode] 消息编码失败:{}", msg.getHead(), e);
            throw new RpcWriteException(e);
        }
    }
}
